#!/usr/bin/env python
# encoding: utf-8


"""
@file: dingyiyu.py
@time: 2017/1/11 下午5:27
"""
# 三角函数的定义域
from mathsolver.functions.base import *
from sympy import fraction
from mathsolver.functions.budengshi import common_opers as co


def domain_of_defin(expr):
    """
    求表达式的定义域 tan, 分式, 根号, log
    :param expr:
    :return:
    """

    class TypeRegs(object):
        Tan = r'tan\(.*?\)'
        Sqrt = r'sqrt\(.*?\)'
        Log = r'log\(.*?\)'

    def is_comp_func(func_expr):
        expr_str = str(func_expr)
        if expr_str.find('tan') >= 0:
            return True
        elif expr_str.find('sqrt') >= 0:
            return True
        elif expr_str.find('log') >= 0:
            return True
        else:
            return False

    expr = sympify(expr)
    ineq_list = []
    mons = expr.as_coefficients_dict().keys()
    for mon in mons:
        mo, de = fraction(mon)
        if not de.is_real:  # 如果分母不为常数
            ineq_list.append([de, '!=', '0'])
            ineq_list.extend(domain_of_defin(de))
        else:
            mo_str = str(mo)
            if mo_str.find('tan') >= 0:
                tan_expr = sympify(co.find_reg_expr(TypeRegs.Tan, mo_str)[0])
                tan_arg = tan_expr.args[0]
                if is_comp_func(tan_arg):
                    ineq_list.extend(domain_of_defin(tan_arg))
                else:
                    ineq_list.append([tan_arg, '!=', sympify('pi/2+k*pi')])
            elif mo_str.find('sqrt') >= 0:
                sqrt_expr = sympify(co.find_reg_expr(TypeRegs.Sqrt, mo_str)[0])
                sqrt_arg = sqrt_expr.args[0]
                if is_comp_func(sqrt_arg):
                    ineq_list.extend(domain_of_defin(sqrt_arg))
                else:
                    ineq_list.append([sqrt_arg, '>=', '0'])
            elif mo_str.find('log') >= 0:
                log_expr = sympify(co.find_reg_expr(TypeRegs.Log, mo_str)[0])
                log_arg = log_expr.args[0]
                ineq_list.extend(domain_of_defin(log_arg))
                if is_comp_func(log_arg):
                    ineq_list.extend(domain_of_defin(log_arg))
                else:
                    ineq_list.append([log_arg, '>', '0'])
    return ineq_list


# 函数y=\\sqrt{2sinx-1}的定义域为().
class DingYiYu001(BaseFunction):
    def solver(self, *args):
        co.comp_func()
        return self


# 三角函数定义域
class SanJiaoHanShuDingYiYu(BaseFunction):
    CLS = [DingYiYu001, ]

    def solver(self, *args):
        for cl in SanJiaoHanShuDingYiYu.CLS:
            try:
                solve_r = cl(verbose=True)
                solve_r.known = self.known
                solve_r = solve_r.solver(*args)
                solve_r.label.add('三角函数定义域')
                break
            except Exception:
                solve_r = None
        if not solve_r:
            raise 'try fail'
        return solve_r
